from rest_framework import serializers

from utils import validates
from .models import Modulars
from projects.models import Projects

class ModularsSerializer(serializers.ModelSerializer):
    """
    模块序列化器
    """
    project = serializers.StringRelatedField(help_text='项目名称')
    project_id = serializers.PrimaryKeyRelatedField(queryset=Projects.objects.all(),
                                                    help_text='项目ID')

    class Meta:
        model = Modulars
        fields = ('id', 'name', 'tester', 'project', 'project_id', 'desc', 'create_time')
        extra_kwargs = {
            'create_time': {
                'read_only': True
            }
        }

    def create(self, validated_data):
        project = validated_data.pop('project_id')
        validated_data['project'] = project
        modulars = Modulars.objects.create(**validated_data)
        return modulars

    def update(self, instance, validated_data):
        if 'project_id' in validated_data:
            project = validated_data.pop('project_id')
            validated_data['project'] = project
        return super().update(instance, validated_data)


class ModularsRunSerializer(serializers.ModelSerializer):
    """
    运行测试模块序列化器
    """
    env_id = serializers.IntegerField(write_only=True,
                                      help_text='环境变量ID',
                                      validators=[validates.whether_existed_env_id])

    class Meta:
        model = Modulars
        fields = ('id', 'env_id')

